#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
基于事件系统的回显插件
"""

from typing import Dict, Optional, Any
from common.logger import logger
from plugins.base_plugin import BasePlugin
from plugins.event_system import Event, EventType, on_message, on_any_message, middleware


class Plugin(BasePlugin):
    """基于事件系统的回显插件类"""
    
    def __init__(self, config: Dict[str, Any], event_bus):
        super().__init__(config, event_bus)
        self.echo_prefix = self.settings.get("echo_prefix", "回显: ")
        self.max_length = self.settings.get("max_length", 100)
    
    @on_message(EventType.MESSAGE_TEXT)
    async def handle_text_message(self, event: Event) -> Optional[Dict[str, Any]]:
        """处理文本消息事件"""
        try:
            # 检查插件是否启用
            if not self.is_enabled():
                return None
            
            data = event.data
            content = data.get("content", "")
            
            # 限制消息长度
            if len(content) > self.max_length:
                content = content[:self.max_length] + "..."
            
            # 构造回显消息
            echo_content = f"{self.echo_prefix}{content}"
            
            logger.info(f"回显插件处理文本消息: {data.get('sender_wxid')} -> {echo_content}")
            
            return self.create_text_response(echo_content)
            
        except Exception as e:
            logger.error(f"回显插件处理文本消息失败: {e}")
            return None
    
    @on_message(EventType.MESSAGE_IMAGE)
    async def handle_image_message(self, event: Event) -> Optional[Dict[str, Any]]:
        """处理图片消息事件"""
        try:
            # 检查插件是否启用
            if not self.is_enabled():
                return None
            
            data = event.data
            sender_wxid = data.get("sender_wxid", "")
            
            logger.info(f"回显插件收到图片消息: {sender_wxid}")
            
            return self.create_text_response(f"{self.echo_prefix}收到一张图片")
            
        except Exception as e:
            logger.error(f"回显插件处理图片消息失败: {e}")
            return None
    
    @on_any_message()
    async def handle_any_message(self, event: Event) -> Optional[Dict[str, Any]]:
        """处理任意消息事件（可选）"""
        try:
            # 检查插件是否启用
            if not self.is_enabled():
                return None
            
            data = event.data
            msg_type = data.get("msg_type", 0)
            sender_wxid = data.get("sender_wxid", "")
            
            # 只处理文本和图片消息，其他消息类型不处理
            if msg_type not in [1, 3]:
                return None
            
            logger.debug(f"回显插件处理任意消息: {msg_type} from {sender_wxid}")
            
        except Exception as e:
            logger.error(f"回显插件处理任意消息失败: {e}")
        
        return None 